/*
 * @Author: guoyangf
 * @Date: 2020-05-28 14:34:28
 * @LastEditTime: 2020-09-15 19:53:36
 * @Description: 作业类组件基类
 */
import { Component } from 'react';
import { base, broadcast, high, cardCache } from 'nc-lightapp-front';
const { getCacheById } = cardCache;
const { NCPagination, NCDiv } = base;
const { BillErrorTrack } = high;
import presetVar from './presetVar';
//控件
import { TabCtrl, ButtonGroupCtrl, SearchCtrl, ListCtrl, SearchTableStatusCtrl, TitleCtrl, ReasonCtrl, IframeCtrl, TakeOrderButtonCtrl, HistoryCtrl, ReasonModalCtrl, RejectModalCtrl } from 'ssccommon/components/job-style/control';
import { tableFieldRender, cardFieldRender } from './data-handle/tableDataHandle';

//布局组件
import { ListPageArea, DetailPageArea, TabBarArea, SearchArea, ListArea, WorkBarArea } from 'ssccommon/components/job-style/layout';
import { searchTplHandle, tableCardTplHandle } from './tplHandle';
import initTemplate from './initTemplate';
import { socketMesg, handleSagaErrorClick } from './events/sagaEvent';
import {
    openBill,
    queryData,
    goBack,
    commonPrint,
    listBtnBeforeEvent,
    btnAfterEvent,
    detailPageStatusHandleByRecord,
    rejectModalConfirmEvent,
    reasonModalSaveSuccessCallback,
    diractionalTakeQuery,
    scrollLoadListData,
    queryDataByPks,
    sortCallback,
    todoTabListPkRefresh,
    getPkListAndTabCount,
    updateTabAndSearchCount,
    setHandleReason,
    checkBillIsEditStatus,
    detailPageHeadBtnBeforeEvent,
    reloadSubPage,
    deleteRowAndRefreshCountByListBtn
} from './events/commonBizEvent'
import tabBarEvent from './events/tabBarEvent';
import searchEvent from './events/searchEvent';
import jobButtonEvent from './events/jobButtonEvent';
import searchCtrlCustomFieldEvent from './events/searchCtrlCustomFieldEvent';
import AuditPointBar from 'ssccommon/components/auditPointBar/AuditPointBar';
import requestApi from './requestApi';
import { tableCardDataHandle, listOprColVisibleBtn } from './data-handle/tableDataHandle';
import { setSearch } from '../../../utils/setComponentUsed';

import './index.less'


class BaseJobComponent extends Component {

    constructor(props, opt) {
        super(props);
        setSearch(props, 'search_Area')

        this.state = {
            multiLang: {},
            activeTabKey: null, //活动标签的的key，也是tabcode
            currentRowBillStatus: null, //当前行的单据状态
            showDetailPage: false, //显示详情页
            approveUrl: '',
            tabData: [ //页签数据
            ],
            searchConfigArr: [ //查询模板，与tab一一对应

            ],
            extendableSearchFieldValueObj: {}, //可扩展的查询字段值。 通过query接口获得，如单据类型
            listConfigArr: [ //列表模板，与tab一一对应

            ],
            sideBarQueryUrl: null, //侧边栏查询接口
            sideBarIsEdit: false, //侧边栏编辑状态
            sideBarIsShowRectify: false, //侧边栏显示整改
            sedeBarRectifyIsEdit: false, //侧边栏整改是否可编辑
            pageNumInDetail: null, //详情页翻页器页码 在openBill和翻页器回调中设置
            isShowTakeOrderBtn: false, //是否显示接单按钮
            tipsInfo: [], //单据编号后边的tips
            handleReason: '', //处理原因： 审批、 驳回、 挂起、取消挂起、 调整、取消调整
            currentRowSagaStatus: null, //当前行的saga状态， 1事物错误  0事物正确。  在openBill方法和saga消息监听中被设置，用于ButtonGroupCtrl控件显示saga图标按钮
            billErrorInfoBySaga: {} //点击saga错误图标（红色感叹号）后，BillErrorTrack组件的配置信息
        }
        this.JobTabBarClickEvent = null;
        this.currentRowData = {};
        this.currentTabPkList = []; //当前页签单据的全部pk
        this.canScrollLoadFlag = true; //是否可以滚动加载数据,控制接口调用次数
        this.lastQueryTime = ''; //上次queryData查询时间
        this.queryParam = {
            "tasktype": null, //在initTemplate文件里获得模板后初始化
            "tabcode": null,
            "pageinfo": {
                "number": 1,
                "size": 20,
                "totalElements": 0,
                "totalPages": 0
            },
            "iscmpreject": "N",
            "orderByInfo": [

            ],
            "querycondition": {

            },
            "querytype": "tree",
            "oid": null
        }

        this.beforeSetMetaAndButton = (meta, buttons) => { //setMeta前对模板的操作。 实际小应用子类里重写该方法

        }
        this.afterSetMetaAndButton = () => { //setMeta后对模板的操作。 实际小应用子类里重写该方法

        }
        this.sscMultiLangPromise = props.sscMultiLangPromise; //多语promise
        this.presetVar = presetVar;
        this.tasktype = null; //从模板中初始化。
        this.requestApi = requestApi;
        this.tabBarEvent = tabBarEvent.bind(this);
        this.searchTplHandle = searchTplHandle.bind(this);
        this.tableCardTplHandle = tableCardTplHandle.bind(this);
        this.goBack = goBack.bind(this);
        this.queryData = queryData.bind(this);
        this.searchEvent = searchEvent.bind(this);
        this.openBill = openBill.bind(this);
        this.jobButtonEvent = jobButtonEvent.call(this);
        this.searchCtrlCustomFieldEvent = searchCtrlCustomFieldEvent.call(this);
        this.commonPrint = commonPrint.bind(this);
        this.listBtnBeforeEvent = listBtnBeforeEvent.bind(this);
        this.btnAfterEvent = btnAfterEvent.bind(this);
        this.rejectModalConfirmEvent = rejectModalConfirmEvent.bind(this);
        this.reasonModalSaveSuccessCallback = reasonModalSaveSuccessCallback.bind(this);
        this.diractionalTakeQuery = diractionalTakeQuery.bind(this);
        this.tableCardDataHandle = tableCardDataHandle.bind(this);
        this.scrollLoadListData = scrollLoadListData.bind(this);
        this.queryDataByPks = queryDataByPks.bind(this);
        this.listOprColVisibleBtn = listOprColVisibleBtn.call(this); //列表操作列可见按钮控制
        this.sortCallback = sortCallback.bind(this);
        this.todoTabListPkRefresh = todoTabListPkRefresh.bind(this);
        this.getPkListAndTabCount = getPkListAndTabCount.bind(this);
        this.updateTabAndSearchCount = updateTabAndSearchCount.bind(this);
        this.setHandleReason = setHandleReason.bind(this);
        this.checkBillIsEditStatus = checkBillIsEditStatus.bind(this);
        this.detailPageHeadBtnBeforeEvent = detailPageHeadBtnBeforeEvent.bind(this);
        this.deleteRowAndRefreshCountByListBtn = deleteRowAndRefreshCountByListBtn.bind(this);
        this.socketMesg = socketMesg.bind(this);
        this.handleSagaErrorClick = handleSagaErrorClick.bind(this);
        this.reloadSubPage = reloadSubPage.bind(this);
        this.tableFieldRender = tableFieldRender.call(this);
        this.cardFieldRender = cardFieldRender.call(this);

        this.setButtonStatus = () => { }; //详情页按钮状态， 由业务实现类实现
        this.updateCurrentRowField = (res) => { } //更新当前行相关字段（ts， taskstatus）， 又业务实现类实现。

        this.sscMultiLangPromise.then((multiLang) => {
            this.setState({
                multiLang
            })
        })
    }

    componentDidMount() {
        initTemplate.call(this, this.props);

        //iframe中的单据为编辑态时，禁止使用翻页控件按钮
        let cardPaginationDom = document.querySelector('.cardPagination-lightapp-component-wrap');
        cardPaginationDom && cardPaginationDom.addEventListener('click', (e) => {
            if (this.checkBillIsEditStatus()) {
                e.stopPropagation();
            }
        })

        //单据内操作时，监听已注册的接口，匹配成功后刷新侧边栏数据和单据的ts
        if (!this.props.disabledBroadcastEvent) { //我的稽核 禁用broadcast事件
            setTimeout(async () => { //降低请求优先级
                let result = await this.requestApi.apiRefreshList() //请求需要刷新的接口列表
                let urlArr = result.data.actionnames;
                broadcast.on('TabBroadcast', async (obj, key) => { //监听ajax事件
                    if (this.state.showDetailPage) { //只在审批详情页面时触发
                        if (urlArr.indexOf(obj.ajaxUrl.slice(9, -3).split('/').join('.')) > -1) {
                            //调用审核侧边栏刷新
                            this.state.sideBarQueryUrl && this.auditPointBarInst.setPointTreeData(this.auditPointBarInst.baseReqParam, true, null, true)
                            //更新ts  否则接口提示：数据已修改，请刷新页面后重试！
                            let result = await this.queryDataByPks([this.currentRowData.pk_task.value]);
                            this.currentRowData.ts.value = result.data.tasklist.rows[0].values.ts.value;

                        }
                    }

                })
            })
        }
    }

    componentWillUpdate() {

    }



    render(bizExtComConfig = {}) { //bizExtComConfig 业务节点自定义组件配置
        const { listAreaBottomCom, detailAreaBottomCom, tabLeftAreaCom = [] } = bizExtComConfig
        let multiLang = this.state.multiLang;

        const {
            cardPagination: { createCardPagination },
        } = this.props;

        const TakeOrderButtonJSX = this.state.activeTabKey == 'todo' && this.state.isShowTakeOrderBtn && <TakeOrderButtonCtrl multiLang={multiLang} />

        const leftArea = [TakeOrderButtonJSX].concat(tabLeftAreaCom);
        return (
            [
                /*列表页*/
                < ListPageArea
                    show={!this.state.showDetailPage}
                >
                    {/* 页签区 */}
                    <TabBarArea>
                        <TabCtrl
                            tabData={this.state.tabData}
                            activeKey={this.state.activeTabKey}
                            tabShowNumbers={null}
                            tabOnChange={this.tabBarEvent}
                            btnLeftCustomArea={leftArea}
                            btnRightCustomArea={null}
                            btnEvent={this.jobButtonEvent}
                        />

                        {/* 定向提取 */}
                        {this.state.useDirectionalTakeOrderBtn && this.props.search.NCCreateSearch(
                            'search_Area',
                            {
                                clickSearchBtn: (props, queryCondition, key) => {
                                    this.diractionalTakeQuery(queryCondition)
                                },
                                onlyShowSuperBtn: true,
                                replaceSuperBtn: <span id='ssc-biz-directional-take-btn'>{multiLang['job-common-search-dxtq']}</span>//这个按钮实际会被隐藏，也可不用加多语
                            }
                        )}
                    </TabBarArea>
                    {/* 查询区 */}
                    <SearchArea>
                        {
                            this.state.searchConfigArr.map((config) => {
                                return (
                                    <SearchCtrl
                                        ref={inst => this[`${config.tabCode}_SearchCtrl`] = inst}
                                        isShow={config.isShow}
                                        searchTplArea={config.searchTplArea}
                                        specialDisplayCondition={config.specialDisplayCondition}
                                        customField={config.customField}
                                        customFieldEvent={this.searchCtrlCustomFieldEvent}
                                        searchEvent={this.searchEvent}
                                        isShowAdvSearchArea={config.isShowAdvSearchArea}
                                        iconBtnEvent={{
                                            showCard: this.props.sscJobConfig.showSwitchCardBtn ?
                                                () => {
                                                    let tabCode = this.state.activeTabKey;
                                                    let listConfigArr = this.state.listConfigArr;
                                                    let targetListConfig = listConfigArr.find(config => config.tabCode == tabCode);
                                                    targetListConfig.showCardList = !targetListConfig.showCardList;
                                                    this.setState({
                                                        listConfigArr
                                                    })
                                                }
                                                :
                                                null
                                        }}
                                        extendableSearchFieldValueObj={this.state.extendableSearchFieldValueObj}
                                    />
                                )
                            })
                        }
                    </SearchArea>
                    {/* 列表区 */}
                    <ListArea>
                        {
                            this.state.listConfigArr.map((config) => {
                                return (

                                    this.state.showDetailPage ?
                                        null :
                                        (
                                            <ListCtrl
                                                ref={inst => this[`${config.tabCode}_ListCtrl`] = inst}
                                                key={config.regTableTplArea}
                                                isShow={config.isShow}
                                                isShowDetailPage={this.state.showDetailPage}
                                                showCardList={config.showCardList}
                                                regTableTplArea={config.regTableTplArea}
                                                rowData={config.firstPageRowData}
                                                cardTpl={config.cardTpl}
                                                cardData={config.cardData}
                                                cardFieldRender={config.cardFieldRender}
                                                oprBtnEvent={this.jobButtonEvent}
                                                oprBtnBeforeEvent={this.listBtnBeforeEvent}
                                                oprBtnAfterEvent={this.btnAfterEvent}
                                                oprBtnTplArea={config.oprBtnTplArea}
                                                oprColBtnsVisibleCtrl={config.oprColBtnsVisibleCtrl}
                                                onRowDoubleClick={this.openBill}
                                                showCheck={this.props.sscJobConfig.isShowTableCheckbox}
                                                listScrollCallback={this.scrollLoadListData}
                                                sortCallback={this.sortCallback}
                                                tableCheckboxOnSelect={config.tableCheckboxOnSelect} //此属性在小应用实例类中通过重写[before|after]SetMetaAndButton，完成配置
                                                sagaIconClickEvent={this.handleSagaErrorClick}
                                                paginationClickEvent={async (tableArea, pks) => {
                                                    this.currentTablePagePks = pks;
                                                    let comPageInfo = this.props.table.getTablePageInfo(tableArea);

                                                    if (this.queryParam.pageinfo.size != comPageInfo.pageSize) {
                                                        this.queryParam.pageinfo.size = comPageInfo.pageSize;
                                                    }
                                                    let result = await this.queryDataByPks(pks);
                                                    //let cardData = this.tableCardDataHandle(null, result.data.taskcard, result.data.tasklist);
                                                    this.props.table.setAllTableData(tableArea, result.data.tasklist);

                                                }}
                                            />
                                        )

                                )
                            })
                        }

                    </ListArea>
                    {listAreaBottomCom}
                </ListPageArea >
                ,
                /*详情页*/
                < DetailPageArea
                    show={this.state.showDetailPage}

                >
                    {/* 顶部工作栏 */}
                    <WorkBarArea>
                        <TitleCtrl
                            title={this.props.getSearchParam('n')}
                            backEvent={this.goBack}
                            multiLang={multiLang}
                            titleMultiLangCode={this.props.sscJobConfig.titleMultiLangCode}
                        />
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            {this.props.sscJobConfig.enableReasonCtrl &&
                                <ReasonCtrl
                                    setHandleReason={this.setHandleReason}
                                    handleReason={this.state.handleReason}
                                />
                            }
                            <ButtonGroupCtrl
                                btnTplArea={'detail'}
                                customBtnData={[]}
                                btnEvent={this.jobButtonEvent}
                                btnBeforeEvent={this.detailPageHeadBtnBeforeEvent}
                                isShowSagaIcon={this.state.currentRowSagaStatus === "1"}
                                sagaIconClickEvent={this.handleSagaErrorClick}
                            />
                            {/* 翻页器 */}

                            {

                                createCardPagination({
                                    handlePageInfoChange: async (props, pk) => {
                                        //let cardData = getCacheById(pk, 'todo');
                                        let result = await this.queryDataByPks([pk]);
                                        let index = null;
                                        this.currentTabPkList.find((opk, i) => {
                                            if (opk == pk) {
                                                index = i;
                                            }
                                        })
                                        let RowObj = result.data.tasklist.rows[0];
                                        this.openBill(RowObj.values, index);


                                    },
                                    dataSource: this.state.activeTabKey
                                })


                            }
                            {/* <NCPagination
                                className="job-pagination"
                                key="job-pagination"
                                first
                                last
                                prev
                                next
                                boundaryLinks
                                items={this.currentTabPkList.length}
                                activePage={this.state.pageNumInDetail}
                                onSelect={async (pos) => {
                                    this.setState({
                                        pageNumInDetail: pos
                                    })

                                    let tabCode = this.state.activeTabKey;
                                    let listConfigArr = this.state.listConfigArr;
                                    let targetListConfig = listConfigArr.find(config => config.tabCode == tabCode);
                                    let rows = targetListConfig.rowData.rows;
                                    let index = pos - 1; //行的数组索引
                                    let currentRowData = rows[index];

                                    if (!currentRowData) {
                                        let result = await this.queryDataByPks([this.currentTabPkList[index]]);
                                        currentRowData = result.data.tasklist.rows[0];
                                        rows[index] = currentRowData; //可能会直接点击最后一页
                                    }
                                    this.openBill(null, index);

                                    if (tabCode == 'todo' && pos == this.currentTabPkList.length) { //查询后续pkList
                                        // alert(11);
                                    }
                                }}
                            /> */}
                        </div>


                    </WorkBarArea>

                    {/* iframe页   */}
                    {this.state.sideBarQueryUrl ?
                        (
                            <AuditPointBar
                                /* showModal为true时，说明是审批详情页面，此时currentRowData才不为null  taskstatus为taken时是未处理单子 */
                                //isEdit={this.state.showDetailPage && this.currentRowData.taskstatus.value == 'taken'}
                                disabledAutoPointTree={this.props.sscAppType == 'sscaudit'}
                                disabledRefresh={this.props.sscAppType == 'sscaudit'} /*我的稽核隐藏刷新按钮*/
                                isEdit={this.state.sideBarIsEdit}
                                ref={auditPointBarInst => this.auditPointBarInst = auditPointBarInst}
                                queryUrl={this.state.sideBarQueryUrl}
                                notJudgeBarHide={true}
                                isShowRectify={this.state.sideBarIsShowRectify}  /* 我的稽核存在整改信息 */
                                rectifyIsEdit={this.state.sedeBarRectifyIsEdit}
                                {...this.props}
                            >
                                <IframeCtrl
                                    src={this.state.approveUrl}
                                />
                            </AuditPointBar>
                        )
                        :
                        (
                            <div style={{flex: 1}}>  {/* 此处必须设置flex为1，否则uclient不兼容 */}
                                <IframeCtrl
                                    src={this.state.approveUrl}
                                />
                            </div>
                        )
                    }


                </DetailPageArea >,
                <HistoryCtrl
                    ref={historyCtrlInst => this.historyCtrlInst = historyCtrlInst}
                    tpl={this.state.historyTpl}
                />
                ,
                //挂起、取消挂起、调整、取消调整
                <ReasonModalCtrl
                    ref={reasonModalCtrlInst => this.reasonModalCtrlInst = reasonModalCtrlInst}
                    confirmBtnName={this.state.reasonModalConfirmBtnName}
                    textareaPlaceholder={this.state.reasonModalTextareaPlaceholder}
                    saveUrl={this.state.reasonModalSaveUrl}
                    reqParam={this.currentGridData}
                    actionType={this.state.reasonModalActionType}
                    tabCode={this.state.activeTabKey}
                    saveSuccessCallback={this.reasonModalSaveSuccessCallback}
                    setHandleReason={this.setHandleReason}
                    handleReason={this.state.handleReason}
                    reasonModalUserJsonData={this.state.reasonModalUserJsonData}
                />,
                <RejectModalCtrl
                    ref={rejectModalCtrlInst => this.rejectModalCtrlInst = rejectModalCtrlInst}
                    creditRuleItems={{}}
                    confirmEvent={this.rejectModalConfirmEvent}
                    setHandleReason={this.setHandleReason}
                    handleReason={this.state.handleReason}
                />,
                <NCDiv className={`tips-fixed--wrapper`} areaCode={NCDiv.config.TipWin}>
                    {
                        [...this.state.tipsInfo]
                    }
                </NCDiv>,
                /* SAGA事件监听 */
                this.props.socket.connectMesg({
                    tableAreaCode: this.state.activeTabKey,
                    billpkname: "busiid",//需要传单据的主键，不然不能显示单据追溯
                    billtypeFromList: "billtypecode",
                    billtype: "",
                    onMessage: this.socketMesg,
                    isShowToast: false
                    // 本地前端调试，请传ip和端口
                    // 打包到测试环境之前 去掉
                    // serverLocation: "172.16.86.11:8883"
                }),
                /* SAGA错误信息展示组件 */
                <BillErrorTrack
                    {...this.state.billErrorInfoBySaga}

                    close={() => this.setState({
                        billErrorInfoBySaga: {
                            show: false
                        }
                    })}
                />,
                <audio src="../../../public/music/ssctp_newbill.mp3" ref={(audio) => { this.audio = audio; }}></audio>
            ])

    }

}

export default BaseJobComponent